//
//  CZDetailController.swift
//  GZWeibo666
//
//  Created by wzz on 15/12/1.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class CZDetailController: UIViewController,UITableViewDelegate,UITableViewDataSource {

   
    override func viewDidLoad() {
        super.viewDidLoad()
        //布局子控件
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.NormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.ForwardCell.rawValue)
        tableView.registerClass(CZDetailCell.self, forCellReuseIdentifier:"CZDetailCell")
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        prepareUI()
    
    }
    
    // MARK: 布局子控件
    func prepareUI() {
        self.view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        let bottomView = CZStatusBottomView()
        bottomView.delegate = self
        view.addSubview(bottomView)
        
//        tableView.addPullToRefreshWithActionHandler { () -> Void in
//            print("加载更多数据")
//        }
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            print("加载更多数据")
            self.loadNetComment()
        }
        messBtn.ff_AlignInner(type: ff_AlignType.CenterLeft, referView: self.headView, size: nil, offset: CGPoint(x: 20, y: 0))
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        
        
        //bottomView 约束
        view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
         view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 44))
          view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        
          view.addConstraint(NSLayoutConstraint(item: bottomView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        
        
        //tableView 约束
        view.addConstraint(NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        
         view.addConstraint(NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: bottomView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        
         view.addConstraint(NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        
         view.addConstraint(NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
    }
    
    
    // MARK: - 数据源/代理

     func numberOfSectionsInTableView(tableView: UITableView) -> Int{
        return 2
    }

     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        if section == 0{
            return 1
        }else if section == 1{
            return modelArr.count
        }
       return 1
    }
    ///设置cell
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusCell
            cell.status = status
            
            cell.bottomView.delegate = self
            
            if cell is CZStatusForwardCell {
                (cell as! CZStatusForwardCell).delegate = self
            }
            return cell
        }
        let cell = tableView.dequeueReusableCellWithIdentifier("CZDetailCell") as! CZDetailCell
        cell.detailStatus = modelArr[indexPath.row]
        
        
        return cell
        
    }
    ///设置头部高度,不然显示不出来
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    {
        if section == 1
        {
            return 44
        }
        return 0
    }

    //设置头部view
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
       
        if section == 1 {
            return headView
        }
        return nil
    }

    // MARK: -评论按钮的点击事件
    func messageClick() {
        loadNetComment()
    }
    //取消选中状态
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
   
    //返回对应cell的行高
    /// 发现行高调用比较频繁,导致多次调用.计算一次,然后保存起来,下次直接返回缓存的行高
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->CGFloat {
       
        if indexPath.section == 0 {
            // 先看看有没有缓存的行高,如果有缓存行高,直接拿来用,没有的话,在计算,并缓存起来
            // 获取对应的模型
            //    let status = statuses![indexPath.row]
            
            if status!.rowHeight != nil {
                //  print("返回会缓存的行高: \(indexPath), rowHeight: \(status.rowHeight!)")
                return status!.rowHeight!
            }
            
            // 能到下面来,说明没有缓存的行高
            
            // 获取cell, 计算行高,并不会显示出来
            let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusCell
            
            // cell计算行高
            let rowHeight = cell.rowHeight(status!)
            
            // 缓存行高
            status!.rowHeight = rowHeight
            
            // 返回行高
            // print("计算行高,indexPath: \(indexPath), rowHeight: \(rowHeight)")
            
            return rowHeight
        }
        
        /// 评论cell的高度
        let detailMessage: CZDetailMessage = modelArr[indexPath.row]
        if detailMessage.rowHeigth != 0 {
            //  print("返回会缓存的行高: \(indexPath), rowHeight: \(status.rowHeight!)")
            return detailMessage.rowHeigth
        }
        let cell = tableView.dequeueReusableCellWithIdentifier("CZDetailCell") as!CZDetailCell
        let rowHeight = cell.rowHeight(detailMessage)
        detailMessage.rowHeigth = rowHeight
        return rowHeight
        
    }
    
    ///刷新评论数据
    func loadNetComment() {
//        bottomIndicator.startAnimating()
        modelArr.removeAll()
        CZNetworkTool.sharedInstance.showComments((self.status?.id)!) { (result, error) -> () in
            
            if (result != nil && result!["comments"] != nil){
                let comments =   result!["comments"] as! [[String:AnyObject]]
                
                for dict in comments{
                    
                    let arr =  CZDetailMessage(dict: dict)
                    self.modelArr.append(arr)
                    
                }
                // 刷新数据
                self.tableView.reloadData()
                //加载完数据取消菊花显示
                 self.tableView.infiniteScrollingView.stopAnimating()
            }
            
        }
    }
    
    //MARK: 模型属性
    var status: CZStatus? {
        didSet {
             ///刷新评论数据
            loadNetComment()
        }
    }
    
    // MARK: - 懒加载
    
//    ///底部菊花
//    private lazy var bottomIndicator : UIActivityIndicatorView = {
//        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
//        indicator.color = UIColor.greenColor()
//        return indicator
//    }()
    ///头部view
    lazy var headView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(colorLiteralRed: 243/255.0, green: 93/255.0, blue: 59/255.0, alpha: 0.7)
        view.sizeToFit()
        view.addSubview(self.messBtn)

        return view
    }()
    
   
    private lazy var tableView : UITableView = UITableView()
    
    
    ///评论按钮点击事件
    lazy var messBtn : UIButton = {
        let button = UIButton()
        button.setTitle("评论", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)

        button.sizeToFit()
      
        button.addTarget(self, action:"messageClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    
    
    // 模型数组
    
    var modelArr : [CZDetailMessage] = []


}
    //MARK: ---代理
extension CZDetailController : statusForwardDelegte, CZStatusBottomViewDelegate {
    func statusForwardDelegte(forwardCell: CZStatusForwardCell) {
        let vc = CZDetailController()
        navigationController?.pushViewController(vc, animated: true)
        vc.title = "微博正文"
         vc.status = forwardCell.status?.retweeted_status;
    }
    
    // MARK: - CZStatusBottomViewDelegate 代理方法
    func CZcommentButtonClick(tag: Int) {
        //        print("在控制器执行")
        let rootVC = CZCommentController()
        rootVC.status = status
        //        rootVC.userName =
        // modal 一个控制器
        presentViewController(UINavigationController(rootViewController: rootVC), animated: true, completion: nil)
        
    }
    
    func CZforwardButtonClick(tag: Int) {

        let rootVC = CZForwardStatusController()
        rootVC.status = status
        presentViewController(UINavigationController(rootViewController: rootVC), animated: true, completion: nil)
    }
}

